package cn.com.ddapp.ddm.adapter;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.Entity;
import cn.com.ddapp.ddm.bean.order.OrderDetail;
import cn.com.ddapp.ddm.enums.OrderEnum;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.LogisticsActivity;
import cn.com.ddapp.ddm.ui.dialog.CommonDialog;
import cn.com.ddapp.ddm.ui.dialog.DialogHelper;
import cn.com.ddapp.ddm.ui.dialog.SmileFaceDialog;
import cn.com.ddapp.ddm.ui.order.PayActivity;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TLog;
import okhttp3.Call;

/**
 * Created by caopenghui on 2016-08-03.
 */
public class OrderAdapter extends BaseAdapter {

    protected Gson gson = new Gson();
    private List<OrderDetail> mOrderDetailLists;
    private Context mContext;
    private String userId;
    private int mStatus;

    public OrderAdapter(List<OrderDetail> orderDetails, Context context, int status) {
        this.mOrderDetailLists = orderDetails;
        this.mContext = context;
        userId = SPUtils.getStringData(mContext, SPUtils.USERID);
        this.mStatus = status;
    }

    @Override
    public int getCount() {
        return mOrderDetailLists.size();
    }

    @Override
    public Object getItem(int i) {
        return mOrderDetailLists.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {

        ViewHolder holder=null;
        if(convertView == null){
            convertView= LayoutInflater.from(mContext).inflate(R.layout.order_item,null);
            holder=new ViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            holder= (ViewHolder) convertView.getTag();
        }
        final OrderDetail orderDetail =   mOrderDetailLists.get(position);
        holder.orderNum.setText(orderDetail.getOrderNum());
        holder.orderStaus.setText(statusTransToDes(orderDetail.getOrderStatus()));
        holder.goodsName.setText(orderDetail.getGoodsName());
        holder.goodsPrice.setText(BaseApplication.getIntstance().getResources().getString(R.string.money_symble)+orderDetail.getPrice()+"");
        holder.goodsNum.setText("x"+orderDetail.getNum()+"");
//        holder.totalAcount.setText(new DecimalFormat("######0.00").format(orderDetail.getNum()*orderDetail.getPrice())+"");
        holder.totalAcount.setText(orderDetail.getOrderAcount()+"");
        holder.amount.setText(new DecimalFormat("######0.00").format(orderDetail.getAmount()));
        String []nUrl=orderDetail.getGoodsImg().split("\\.");
        StringBuffer buffer=new StringBuffer();
        buffer.append(nUrl[0]).append("_360.jpg");
        System.out.println("orderDetail.getGoodsImg() == "+orderDetail.getGoodsImg()+"buffer == "+buffer);
        Glide.with(mContext).load(OKUtilAPI.imgBaseUrl+buffer).into(holder.goodsLogo);

        View top = convertView.findViewById(R.id.top);
        View bottom = convertView.findViewById(R.id.bottom);
        View bottom1 = convertView.findViewById(R.id.bottom1);
        View line = convertView.findViewById(R.id.line);

        if(orderDetail.getFirst()){
            top.setVisibility(View.VISIBLE);
            holder.topLine.setVisibility(View.VISIBLE);
        }else{
            top.setVisibility(View.GONE);
            holder.topLine.setVisibility(View.GONE);
        }
        if(orderDetail.getLast()){
            bottom.setVisibility(View.VISIBLE);
            bottom1.setVisibility(View.VISIBLE);
        }else{
            bottom.setVisibility(View.GONE);
            bottom1.setVisibility(View.GONE);
        }

        if(orderDetail.getOrderStatus()==1){
            holder.action1.setText(BaseApplication.getIntstance().getResources().getString(R.string.action1));
            holder.action2.setText(BaseApplication.getIntstance().getResources().getString(R.string.action2));
            holder.action1.setVisibility(View.VISIBLE);
            holder.action2.setVisibility(View.VISIBLE);
            holder.action3.setVisibility(View.GONE);
            holder.action1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, PayActivity.class);
                    intent.putExtra("orderNo",orderDetail.getOrderNum());
                    intent.putExtra("goodsName",orderDetail.getGoodsName());
                    mContext.startActivity(intent);
                }
            });
            holder.action2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    cancelOrder(orderDetail.getOrderId());
                }
            });
            line.setVisibility(View.VISIBLE);
        }else  if(orderDetail.getOrderStatus()==2){
            holder.action1.setText(BaseApplication.getIntstance().getResources().getString(R.string.action3));
            holder.action2.setVisibility(View.GONE);
            holder.action1.setVisibility(View.VISIBLE);
            holder.action3.setVisibility(View.GONE);
            holder.action1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    remindOrder(orderDetail.getOrderId());
                }
            });
            line.setVisibility(View.VISIBLE);
        }else  if(orderDetail.getOrderStatus()==3){
            holder.action1.setText(BaseApplication.getIntstance().getResources().getString(R.string.action6));
            holder.action2.setText(BaseApplication.getIntstance().getResources().getString(R.string.action5));
            holder.action1.setVisibility(View.VISIBLE);
            holder.action2.setVisibility(View.VISIBLE);
            holder.action3.setVisibility(View.GONE);
            holder.action1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    comfirmOrder(orderDetail.getOrderId());
                }
            });
            holder.action2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    LogisticsActivity.startIntent(mContext,orderDetail.getLogisticsCode(),orderDetail.getOrderNum(),orderDetail.getCreateTime());
                }
            });
            line.setVisibility(View.VISIBLE);
        }else  if(orderDetail.getOrderStatus()==4){
            holder.action1.setText(BaseApplication.getIntstance().getResources().getString(R.string.action5));
            holder.action2.setText(BaseApplication.getIntstance().getResources().getString(R.string.action9));
            holder.action1.setVisibility(View.VISIBLE);
            holder.action2.setVisibility(View.VISIBLE);
            holder.action3.setVisibility(View.GONE);
            holder.action1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    LogisticsActivity.startIntent(mContext,orderDetail.getLogisticsCode(),orderDetail.getOrderNum(),orderDetail.getCreateTime());
                }
            });
            holder.action2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    cancelOrder(orderDetail.getOrderId());
                }
            });
            line.setVisibility(View.VISIBLE);
        }else  if(orderDetail.getOrderStatus()==9){
            holder.action1.setText(BaseApplication.getIntstance().getResources().getString(R.string.action9));
            holder.action1.setVisibility(View.VISIBLE);
            holder.action2.setVisibility(View.GONE);
            holder.action3.setVisibility(View.GONE);
            holder.action1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    cancelOrder(orderDetail.getOrderId());
                }
            });
            line.setVisibility(View.VISIBLE);
        }

        return convertView;
    }




    /**
     * 提醒发货
     * @param orderId
     */
    private void remindOrder(Integer orderId) {
        final OkUtilCallback okUtilCallback = new OkUtilCallback(){
            @Override
            public void onMyResponse(String response, int id) {
                TLog.log("orderAdapter",response);
                Entity entity = gson.fromJson(response,Entity.class);
                if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    SmileFaceDialog dialog =  DialogHelper.getPinterestSmileDialogCancelable(mContext);
                    dialog.show();
                }
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                System.out.println(e.getMessage());
                BaseApplication.showToast("错误");
            }
        };
        OKUtilAPI.post(OKUtilAPI.order_tips, "userId="+userId+"&orderId="+orderId, okUtilCallback);
//        BaseApplication.getIntstance().showToast("已成功通知卖家", Toast.LENGTH_SHORT,0, Gravity.CENTER);
    }

    /**
     * 确认收货
     * @param orderId
     */
    private void comfirmOrder(final Integer orderId){

        final CommonDialog dialog = DialogHelper
                .getPinterestDialogCancelable(mContext);
        dialog.setTitle("是否确认收货？");
        dialog.setNegativeButton(BaseApplication.getIntstance().getResources().getString(R.string.cancel), null);
        dialog.setPositiveButton(BaseApplication.getIntstance().getResources().getString(R.string.OK),new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
                BaseActivity activity = (BaseActivity)mContext;
                activity.showWaitDialog(BaseApplication.getIntstance().getString(R.string.order_accept));
                final OkUtilCallback okUtilCallback = new OkUtilCallback(){
                    @Override
                    public void onMyResponse(String response, int id) {
                        BaseActivity activity = (BaseActivity)mContext;
                        activity.hideWaitDialog();
                        TLog.log("orderAdapter",response);
                        Entity entity = gson.fromJson(response,Entity.class);
                        if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                            BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                        }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                            if(mStatus==3){
                                //确认收货后的更新页面如果是待收货栏则移除
                                List<OrderDetail> orderDetailsRemove = new ArrayList<>();
                                for(OrderDetail orderDetail : mOrderDetailLists){
                                    if(orderDetail.getOrderId()==orderId.intValue()){
                                        orderDetailsRemove.add(orderDetail);
                                    }
                                }
                                mOrderDetailLists.removeAll(orderDetailsRemove);
                                OrderAdapter.this.notifyDataSetChanged();
                            }else if(mStatus==0){
                                //确认收货后的更新页面如果是全部则更新UI
                                for(OrderDetail orderDetail : mOrderDetailLists){
                                    if(orderDetail.getOrderId()==orderId.intValue()){
                                        orderDetail.setStatus(4);
                                    }
                                }
                                OrderAdapter.this.notifyDataSetChanged();
                            }

                        }
                    }
                };
                OKUtilAPI.post(OKUtilAPI.orderAccept, "userId=" + userId+"&id="+orderId, okUtilCallback);
            }
        });
        dialog.show();

    }


    /**
     * 取消订单
     * @param orderId
     */
    private void cancelOrder(final Integer orderId) {

        final CommonDialog dialog = DialogHelper
                .getPinterestDialogCancelable(mContext);
        dialog.setTitle("您确定删除该订单？");
        dialog.setNegativeButton(BaseApplication.getIntstance().getResources().getString(R.string.cancel), null);
        dialog.setPositiveButton(BaseApplication.getIntstance().getResources().getString(R.string.OK),new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
                BaseActivity activity = (BaseActivity)mContext;
                activity.showWaitDialog(BaseApplication.getIntstance().getString(R.string.order_cancel));
                final OkUtilCallback okUtilCallback = new OkUtilCallback(){
                    @Override
                    public void onMyResponse(String response, int id) {
                        BaseActivity activity = (BaseActivity)mContext;
                        activity.hideWaitDialog();
                        TLog.log("orderAdapter",response);
                        Entity entity = gson.fromJson(response,Entity.class);
                        if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                            BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                        }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                            //取消订单后的操作
                            List<OrderDetail> orderDetailsRemove = new ArrayList<>();
                            for(OrderDetail orderDetail : mOrderDetailLists){
                                if(orderDetail.getOrderId()==orderId.intValue()){
                                    orderDetailsRemove.add(orderDetail);
                                }
                            }
                            mOrderDetailLists.removeAll(orderDetailsRemove);
                            OrderAdapter.this.notifyDataSetChanged();
                            Intent intent = new Intent();
                            intent.setAction("updata");
                            mContext.sendBroadcast(intent);
                        }
                    }
                };
                OKUtilAPI.post(OKUtilAPI.orderCancel, "userId=" + userId+"&id="+orderId, okUtilCallback);
            }
        });
        dialog.show();
    }

    /**
     *
     * @return
     */
    private String statusTransToDes(Integer status) {
        if(status==null)return "";
        if(status== OrderEnum.NEW.ordinal()){
            return BaseApplication.getIntstance().getResources().getString
                    (R.string.order_pay_waiting);
        }
        if(status==OrderEnum.PAYED.ordinal()){
            return BaseApplication.getIntstance().getResources().getString
                    (R.string.order_sending_waiting);
        }
        if(status==OrderEnum.SENDED.ordinal()){
            return BaseApplication.getIntstance().getResources().getString
                    (R.string.order_receive_waiting);
        }
        if(status==OrderEnum.ACCEPTED.ordinal()){
            return BaseApplication.getIntstance().getResources().getString
                    (R.string.order_finish);
        }
        if(status==9){
            return BaseApplication.getIntstance().getResources().getString(R.string.close);
        }


        return BaseApplication.getIntstance().getResources().getString
                (R.string.aftersaleing);
    }
    static class ViewHolder{
        TextView orderNum;
        TextView orderStaus;
        ImageView goodsLogo;
        TextView goodsName;
        TextView goodsPrice;
        TextView goodsNum;
        TextView totalAcount;
        TextView amount;
        TextView action1;
        TextView action2;
        TextView action3;
        View topLine;
        public ViewHolder(View view){
            orderNum = (TextView)view.findViewById(R.id.orderNum);
            orderStaus = (TextView)view.findViewById(R.id.orderStaus);
            goodsName = (TextView)view.findViewById(R.id.goodsName);
            goodsPrice = (TextView)view.findViewById(R.id.goodsPrice);
            goodsNum = (TextView)view.findViewById(R.id.goodsNum);
            totalAcount = (TextView)view.findViewById(R.id.totalAcount);
            amount = (TextView)view.findViewById(R.id.amount);
            action1 = (TextView)view.findViewById(R.id.action1);
            action2 = (TextView)view.findViewById(R.id.action2);
            action3 = (TextView)view.findViewById(R.id.action3);
            goodsLogo = (ImageView)view.findViewById(R.id.goodsLogo);
            topLine = (View)view.findViewById(R.id.topLine);
        }
    }

}
